package org.cargloss.cp.controller.modul.news;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import org.cargloss.cp.model.News;

import util.hibernate.DAO;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;


public class ActionCrud extends ActionSupport {

	private static final long serialVersionUID = -5933849517817526086L;

	private int id;
	private String createdBy;
	private String modifiedBy;
	private String title;
	private String content;
	private String user;
	Date date = new Date();
	Timestamp time = new Timestamp(date.getTime());

	private Timestamp getNow() {
		Calendar calendar = Calendar.getInstance();
		Date now = calendar.getTime();
		return new Timestamp(now.getTime());
	}

	public String insert() {
		DAO<Integer> dao = new DAO<Integer>();
		News object = new News();
		
		Map<String, Object> sessionMap = ActionContext.getContext().getSession();
		user = (String) sessionMap.get("userName");
		object.setTitle(getTitle());
		object.setContent(getContent());
		object.setCreatedBy(user);
		object.setModifiedBy(user);
		object.setCreatedDate(getNow());
		object.setModifiedDate(getNow());

		dao.insert(object);
		dao.close();
		return "empty";
	}

	public String update() {

		DAO<Integer> dao = new DAO<Integer>();
		News object = (News) dao.find(News.class, Integer.valueOf(getId()));

		object.setTitle(getTitle());
		object.setContent(getContent());
		Map<String, Object> sessionMap = ActionContext.getContext().getSession();
		user = (String) sessionMap.get("userName");
		object.setModifiedBy(user);
		object.setCreatedDate(getNow());
		object.setModifiedDate(getNow());
		dao.update(object);
		dao.close();
		return "empty";
	}

	public String delete() {
		DAO<Integer> dao = new DAO<Integer>();
		News delete = (News) dao.find(News.class, Integer.valueOf(getId()));
		dao.delete(delete);
		dao.close();
		return "empty";
	}

	public String getCreatedBy() {
		return createdBy;
	}

	public void setCreatedBy(String createdBy) {
		this.createdBy = createdBy;
	}

	public String getModifiedBy() {
		return modifiedBy;
	}

	public void setModifiedBy(String modifiedBy) {
		this.modifiedBy = modifiedBy;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getId() {
		return id;
	}

	// validasi
	// public void validate() {
	// if (title == null || title.trim().equals("")) {
	// addFieldError("title", "The name is required");
	// }
	//
	// }

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

}
